package com.ruoyi.web.controller.chargepile;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.chargepile.domain.ChargePile;
import com.ruoyi.chargepile.domain.ChargeRecords;
import com.ruoyi.chargepile.domain.RepairRecord;
import com.ruoyi.chargepile.domain.enums.RolesEnum;
import com.ruoyi.chargepile.domain.vo.OnlyOneQueryValue;
import com.ruoyi.chargepile.service.ChargePileService;
import com.ruoyi.chargepile.service.ChargeRecordsService;
import com.ruoyi.chargepile.service.RepairRecordService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.util.DateRange;
import com.ruoyi.util.Pages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 充电桩 前端控制器
 * </p>
 *
 * @author zxc
 * @since 2024-07-03
 */
@RestController
@RequestMapping("/charge-pile")
public class ChargePileController {

    @Autowired
    private ChargePileService chargePileService;

    @Autowired
    private ChargeRecordsService chargeRecordsService;

    @Autowired
    private RepairRecordService repairRecordService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @PostMapping("/addChargePile")
    public AjaxResult addChargePile(@RequestBody ChargePile chargePile) {
        if(chargePileService.save(chargePile)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    @PostMapping("/updateChargePile")
    public AjaxResult updateChargePile(@RequestBody ChargePile chargePile) {
        if(chargePileService.updateById(chargePile)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    @GetMapping("/checkIsDel/{chargePileId}")
    public AjaxResult checkIsDel(@PathVariable Integer chargePileId) {
        // 是否有充电记录
        LambdaQueryWrapper<ChargeRecords> chargeRecordsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chargeRecordsLambdaQueryWrapper
                .eq(ChargeRecords::getChargePileId, chargePileId);
        long chargeRecordCount = chargeRecordsService.count(chargeRecordsLambdaQueryWrapper);

        // 是否有维修记录
        LambdaQueryWrapper<RepairRecord> repairRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        repairRecordLambdaQueryWrapper
                .eq(RepairRecord::getChargePileId, chargePileId);
        long repairRecordCount = repairRecordService.count(repairRecordLambdaQueryWrapper);

        if(chargeRecordCount > 0 || repairRecordCount > 0){
            return AjaxResult.error("此充电桩已有数据，无法删除");
        }

        return AjaxResult.success();
    }

    @PostMapping("/delChargePile/{chargePileIds}")
    public AjaxResult delChargePile(@PathVariable Integer[] chargePileIds) {
        List<Integer> ids = Arrays.stream(chargePileIds)
                .collect(Collectors.toList());

        LambdaQueryWrapper<ChargePile> chargePileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chargePileLambdaQueryWrapper
                .in(ChargePile::getId, ids);

        if(chargePileService.removeBatchByIds(ids)){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    @GetMapping("/getChargePile/{chargePileId}")
    public AjaxResult getChargePile(@PathVariable Integer chargePileId) {
        return AjaxResult.success(chargePileService.getById(chargePileId));
    }

    @GetMapping("/listChargePile")
    public AjaxResult listChargePile(Pages pages, DateRange dateRange, ChargePile chargePile) {
        PageHelper.startPage(pages.getPageNum(), pages.getPageSize());

        LambdaQueryWrapper<ChargePile> chargePileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chargePileLambdaQueryWrapper
                .eq(StringUtils.isNotEmpty(chargePile.getTypes()), ChargePile::getTypes, chargePile.getTypes())
                .like(StringUtils.isNotEmpty(chargePile.getNumber()), ChargePile::getNumber, chargePile.getNumber())
                .eq(StringUtils.isNotEmpty(chargePile.getStatus()), ChargePile::getStatus, chargePile.getStatus())
                .orderByDesc(ChargePile::getId)
                .between(dateRange.getBeginTime() != null, ChargePile::getInstallDate, dateRange.getBeginTime(), dateRange.getEndTime());


        List<ChargePile> list = chargePileService.list(chargePileLambdaQueryWrapper);

        return AjaxResult.success(new PageInfo<ChargePile>(list));
    }

    @GetMapping("/listRepairPileNumber")
    public AjaxResult listRepairPileNumber() {
        Integer userId = null;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<SysRole> sysRoles = iSysRoleService.selectRolesByUserId(sysUser.getUserId());
        List<String> collectRoleKey = sysRoles.stream()
                .map(item -> item.getRoleKey())
                .collect(Collectors.toList());
        if (!collectRoleKey.contains(RolesEnum.ADMIN.getCode()) && !collectRoleKey.contains(RolesEnum.ADMINISTRATOR.getCode())){
            userId = Math.toIntExact(sysUser.getUserId());
        }
        List<OnlyOneQueryValue> queryNumber = chargePileService.listRepairPileNumber(userId);
        return AjaxResult.success(queryNumber);
    }

    @GetMapping("/listChargeRecordsPileNumber")
    public AjaxResult listChargeRecordsPileNumber() {
        Integer userId = null;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<SysRole> sysRoles = iSysRoleService.selectRolesByUserId(sysUser.getUserId());
        List<String> collectRoleKey = sysRoles.stream()
                .map(item -> item.getRoleKey())
                .collect(Collectors.toList());
        if (!collectRoleKey.contains(RolesEnum.ADMIN.getCode()) && !collectRoleKey.contains(RolesEnum.ADMINISTRATOR.getCode())){
            userId = Math.toIntExact(sysUser.getUserId());
        }
        List<OnlyOneQueryValue> queryNumber = chargePileService.listChargeRecordsPileNumber(userId);
        return AjaxResult.success(queryNumber);
    }

}

